package com.jsyl.web.controller.authority;


import com.alibaba.fastjson.JSONObject;
import com.jsyl.application.authority.*;
import com.jsyl.entity.authority.*;
import com.jsyl.entity.request.AuditoryRequest;
import com.jsyl.infra.utils.page.PageModel;
import com.jsyl.web.utils.DataTablesPageModel;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 *
 *
 */
@Controller
@RequestMapping("/teacher")
public class TeacherController {

    @Autowired
    private IChildApplication childApplication;

    @Autowired
    private ITeaherApplication teaherApplication;

    @Autowired
    private IClassScheduleApplication classScheduleApplication;

    @Autowired
    private ISensoryIntegrationApplication sensoryIntegrationApplication;

    @Autowired
    private IAvailableVisualProjectsApplication availableVisualProjectsApplication;

    @Autowired
    private IScheduleProjectSubjectApplication scheduleProjectSubjectApplication;

    @Autowired
    private IChildAbilityFeedbackConfigApplication childAbilityFeedbackConfigApplication;

    @Autowired
    protected HttpServletRequest request;

    @Autowired
    private ICenterApplication centerApplication;

    private final static String USERNAME = "admin";

    private final static String PASSWORD = "admin";

    //用来存标识在缓存
    private final static String CONTINUE = "Continue";


    @RequestMapping("/sign")
    public Object sign() {
        return "login";
    }


    /**
     * 登录操作
     *
     * @param userName   账户
     * @param password   密码
     * @param rememberMe 记住我
     * @return
     */
    @RequestMapping("/login")
    public String login(@RequestParam("username") String userName, @RequestParam("password") String password,
                        @RequestParam(value = "rememberme", required = false) String rememberMe, Model model) {
        if (StringUtils.isEmpty(userName)) {
            model.addAttribute("login_error_info", "用户名不能为空！");
            return "login";
        }
        if (StringUtils.isEmpty(password)) {
            model.addAttribute("login_error_info", "密码不能为空！");
            return "login";
        }
        if (userName.equals(USERNAME) && password.equals(PASSWORD)) {
            HttpSession session = request.getSession();
            session.setAttribute(CONTINUE, CONTINUE);
            //设置session时间 30分钟后销毁
            session.setMaxInactiveInterval(30*60);

            List centernameList = classScheduleApplication.findCenter();
            model.addAttribute("centernameList", centernameList);
            return "index/teacher-page";
        } else {
            model.addAttribute("login_error_info", "账号或者密码错误");
            return "login";
        }
    }


    /**
     * 跳到分页页面
     *
     * @param model Model
     * @return Object
     */
    @RequestMapping("/goTeacherPage")
    public Object goTeacherPage(Model model) {
       if (!Continue()){
           return "login";
       }
        List centernameList = classScheduleApplication.findCenter();
        model.addAttribute("centernameList", centernameList);
        return "index/teacher-page";
    }

    @ResponseBody
    @RequestMapping("/getdata")
    public PageModel<ClassSchedule> queryModel(ClassSchedule classSchedule, DataTablesPageModel<ClassSchedule> pm, HttpServletRequest request) {
        pm = (DataTablesPageModel<ClassSchedule>) teaherApplication.query(pm, classSchedule);
        return pm;
    }

    @ResponseBody
    @RequestMapping("/getCenterData")
    public PageModel<ClassSchedule> getCenterData(ClassSchedule classSchedule, DataTablesPageModel<ClassSchedule> pm, HttpServletRequest request) {
        pm = (DataTablesPageModel<ClassSchedule>) centerApplication.query(pm, classSchedule);
        return pm;
    }

    /**
     * 获取老师的名字
     */
    @ResponseBody
    @RequestMapping("getTeacherData")
    public PageModel<ClassSchedule> goChildData(ClassSchedule classSchedule, DataTablesPageModel<ClassSchedule> pm, HttpServletRequest request) {
        String centerId = request.getParameter("centerId");
        classSchedule.setCenterId(centerId);
        pm = (DataTablesPageModel<ClassSchedule>) teaherApplication.query(pm, classSchedule);
        return pm;
    }

    /**
     * 获取孩子名字
     */
    @ResponseBody
    @RequestMapping("getChildData")
    public PageModel<Child> getChildData(Child child, DataTablesPageModel<Child> pm, HttpServletRequest request) {
        pm = (DataTablesPageModel<Child>) childApplication.query(pm, child);
        return pm;
    }


    /**
     * 获取孩子名字 老师纬度
     */
    @ResponseBody
    @RequestMapping("getTeacherChildData")
    public PageModel<Child> getTeacherChildData(Child child, DataTablesPageModel<Child> pm, HttpServletRequest request) {
        pm = (DataTablesPageModel<Child>) childApplication.query(pm, child);
        return pm;
    }


    /**
     * 获取孩子数据
     */
    @ResponseBody
    @RequestMapping("getSearchChildData")
    public List<Child> getSearchChildData(Child child, HttpServletRequest request) {
        return childApplication.getSearchChildData(child);
    }


    //跳到孩子页面
    @RequestMapping("/goStudentPage")
    public String goStudentPage(Model model, HttpServletRequest request) {
        if (!Continue()){
            return "login";
        }
        if (null != request.getParameter("centerId") && !request.getParameter("centerId").equals("")) {
            String centerId = request.getParameter("centerId");
            ClassSchedule classSchedule = classScheduleApplication.getByField("centerId", centerId);
            if (null != classSchedule.getCenterName()) {
                String centerName = classSchedule.getCenterName();
                model.addAttribute("centerId", centerId);
                model.addAttribute("centerName", centerName);
            }
        }
        if (null != request.getParameter("teacherId") && !request.getParameter("teacherId").equals("")) {
            String teacherId = request.getParameter("teacherId");
            ClassSchedule classSchedule = classScheduleApplication.getByField("teacherId", teacherId);
            String centerId = classSchedule.getCenterId();
            String centerName = classSchedule.getCenterName();
            String teachername = classSchedule.getTeacherName();
            //获得老师的姓名，信息
            model.addAttribute("centerId", centerId);
            model.addAttribute("teacherId", teacherId);
            model.addAttribute("teachername", teachername);
            model.addAttribute("centerName", centerName);
            return "index/child-teacher-page";
        }
        return "index/child-page";
    }

    //跳到课程页面
    @RequestMapping("/goSchedulePage")
    public String goSchedulePage(Model model, HttpServletRequest request) {
        if (!Continue()){
            return "login";
        }
        String childId = request.getParameter("childId");
        if (null!=childId && !childId.equals("")){
            Child child = childApplication.get(childId);
            String year = child.getYear();
            String month = child.getMonth();
            //年龄
            String age = "0岁";
            if (null != year && !year.equals("")) {
                if (null != month && !month.equals("")) {
                    String birthday = year + month;
                    try {
                        age = getAge(birthday);
                    } catch (ParseException e) {
                        age = "0岁";
                    }
                } else {
                    String birthday = year + "01";
                    try {
                        age = getAge(birthday);
                    } catch (ParseException e) {
                        age = "0岁";
                    }
                }
            }
            String grade = child.getGrade();
            if (null != grade && !grade.equals("")) {
                if (grade.equals("0")) {
                    child.setGrade("学前");
                } else {
                    child.setGrade(grade + "年级");
                }
            } else {
                child.setGrade("未设置");
            }
            model.addAttribute("age", age);
            model.addAttribute("child", child);
        }
//        return "index/schedule-page";
                return "index/class-schedule";
    }


    //跳到课程页面
    @RequestMapping("/goScheduleProPage")
    public String goScheduleProPage(Model model, HttpServletRequest request) {
        if (!Continue()) {
            return "login";
        }
        String childId = request.getParameter("childId");
        String scheduleId = request.getParameter("scheduleId");
        if (null != childId && !childId.equals("")) {
            Child child = childApplication.get(childId);
            String year = child.getYear();
            String month = child.getMonth();
            //年龄
            String age = "0岁";
            if (null != year && !year.equals("")) {
                if (null != month && !month.equals("")) {
                    String birthday = year + month;
                    try {
                        age = getAge(birthday);
                    } catch (ParseException e) {
                        age = "0岁";
                    }
                } else {
                    String birthday = year + "01";
                    try {
                        age = getAge(birthday);
                    } catch (ParseException e) {
                        age = "0岁";
                    }
                }
            }
            String grade = child.getGrade();
            if (null != grade && !grade.equals("")) {
                if (grade.equals("0")) {
                    child.setGrade("学前");
                } else {
                    child.setGrade(grade + "年级");
                }
            } else {
                child.setGrade("未设置");
            }
            model.addAttribute("scheduleId", scheduleId);
            model.addAttribute("age", age);
            model.addAttribute("child", child);
        }
        return "index/schedule-page";
    }




    //获得课程数据
    @ResponseBody
    @RequestMapping("/getClassScheduleData")
    public PageModel<ClassSchedule> getClassScheduleData(ClassSchedule classSchedule, DataTablesPageModel<ClassSchedule> pm, HttpServletRequest request) {
        pm = (DataTablesPageModel<ClassSchedule>) classScheduleApplication.query(pm, classSchedule);
        return pm;
    }

    //获得课程数据
    @ResponseBody
    @RequestMapping("/getScheduleData")
    public PageModel<SensoryIntegration> getScheduleData(SensoryIntegration sensoryIntegration, DataTablesPageModel<SensoryIntegration> pm, HttpServletRequest request) {
        pm = (DataTablesPageModel<SensoryIntegration>) sensoryIntegrationApplication.query(pm, sensoryIntegration);
        return pm;
    }

    /**
     * 跳到听觉能力修改页面
     *
     * @param model Model
     * @return Object
     */
    @RequestMapping("/goAuditoryAbilityPage")
    public String goAuditoryAbilityPage(Model model) {
        String code = request.getParameter("code");
        String childId =request.getParameter("childId");
        String scheduleId =request.getParameter("scheduleId");
        Child child =childApplication.get(childId);
        //获得项目名字
        SensoryIntegration sensoryIntegration = sensoryIntegrationApplication.getByField("code",code);
        //获得难度
        Map<String, Object> configParam = new HashMap<String, Object>();
        configParam.put("childId",childId);
        configParam.put("name","dqdj");
        ChildAbilityFeedbackConfig ability = childAbilityFeedbackConfigApplication.getByFields(configParam);
        model.addAttribute("ability", ability);
        model.addAttribute("sensoryIntegration", sensoryIntegration);
        model.addAttribute("child", child);
        model.addAttribute("scheduleId", scheduleId);
        return "index/auditory-ability";
    }

    /**
     * 跳到视觉能力增加页面
     *
     * @param model Model
     * @return Object
     */
    @RequestMapping("/goVisualAdd")
    public String goVisualAdd(Model model) {
        String childId =request.getParameter("childId");
        String code = request.getParameter("code");
        String scheduleId =request.getParameter("scheduleId");
        List<SensoryIntegration> project = sensoryIntegrationApplication.findVisual(childId);
        //获得项目名字
        SensoryIntegration sensoryIntegration = sensoryIntegrationApplication.getByField("code",code);
        Child child =childApplication.get(childId);
        model.addAttribute("dqnlnlMap",getDqnlnlMap());
        model.addAttribute("dqnlnjMap", getDqnlnjMap());
        model.addAttribute("dqnddjMap", getDqnddjMap());
        model.addAttribute("sensoryIntegration", sensoryIntegration);
        model.addAttribute("child", child);
        model.addAttribute("projects", project);
        model.addAttribute("scheduleId", scheduleId);
        return "index/visual-add";
    }


    //听觉项目修改
    @RequestMapping("/auditoryMerge")
    @ResponseBody
    public JSONObject auditoryMerge(AuditoryRequest request) {
        return sensoryIntegrationApplication.auditoryMerge(request);
    }

    //视觉项目增加
    @RequestMapping("/visualAdd")
    @ResponseBody
    public JSONObject visualAdd(AuditoryRequest request) {
        return sensoryIntegrationApplication.visualAdd(request);
    }

    /**
     * 跳到视觉能力修改页面
     *
     * @param model Model
     * @return Object
     */
    @RequestMapping("/goVisualAbilityPage")
    public String goVisualAbilityPage(Model model, DataTablesPageModel<SensoryIntegration> pm) {
        String code = request.getParameter("code");
        String childId =request.getParameter("childId");
        String scheduleId =request.getParameter("scheduleId");
        Integer childIdval =Integer.parseInt(childId);
        Child child =childApplication.get(childId);
        //获得项目名字
        SensoryIntegration sensoryIntegration = sensoryIntegrationApplication.getByField("code",code);
        //获得难度 "dqnlnl"，"dqnlnj"，"dqnddj"，"vqt"，"ljtgcs"
        sensoryIntegration.setChildId(childIdval);
        sensoryIntegration.setCode(code);
        //获得难度
        pm = (DataTablesPageModel<SensoryIntegration>) sensoryIntegrationApplication.query(pm, sensoryIntegration);

        //获得难度
        model.addAttribute("dqnlnlMap",getDqnlnlMap());
        model.addAttribute("dqnlnjMap", getDqnlnjMap());
        model.addAttribute("dqnddjMap", getDqnddjMap());
        model.addAttribute("vqtMap",getVqtMap());
        model.addAttribute("dqnlnlVal", pm.getData().get(0).getDqnlnl());
        model.addAttribute("dqnlnjVal", pm.getData().get(0).getDqnlnj());
        model.addAttribute("dqnddjVal", pm.getData().get(0).getDqnddj());
        model.addAttribute("vqtVal", pm.getData().get(0).getVqt());
        model.addAttribute("ljtgcsVal", pm.getData().get(0).getLjtgcs());
        model.addAttribute("sensoryIntegration", sensoryIntegration);
        model.addAttribute("child", child);
        model.addAttribute("scheduleId", scheduleId);
        return "index/visuals-ability";
    }

    //视觉能力修改
    @RequestMapping("/visualMerge")
    @ResponseBody
    public JSONObject visualMerge(AuditoryRequest request) {
        return sensoryIntegrationApplication.visualMerge(request);
    }


    /**
     * 跳到视觉能力修改页面
     *
     * @param model Model
     * @return Object
     */
    @RequestMapping("/goVisualReplace")
    public String goVisualReplace(Model model) {
        String childId =request.getParameter("childId");
        String code = request.getParameter("code");
        String scheduleId =request.getParameter("scheduleId");
        SensoryIntegration sensoryIntegration = sensoryIntegrationApplication.getByField("code",code);

        List<SensoryIntegration> project = sensoryIntegrationApplication.findVisual(childId);
        Child child =childApplication.get(childId);
        model.addAttribute("dqnlnlMap",getDqnlnlMap());
        model.addAttribute("dqnlnjMap", getDqnlnjMap());
        model.addAttribute("dqnddjMap", getDqnddjMap());
        model.addAttribute("child", child);
        model.addAttribute("projects", project);
        model.addAttribute("sensoryIntegration", sensoryIntegration);
        model.addAttribute("scheduleId", scheduleId);
        return "index/visual-replace";
    }

    //视觉能力修改
    @RequestMapping("/visualReplace")
    @ResponseBody
    public JSONObject visualReplace(AuditoryRequest request) {
        return sensoryIntegrationApplication.visualReplace(request);
    }

    private String getAge(String birthday) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
        Date date = new Date();
        String nowdata = sdf.format(date);
        Calendar bef = Calendar.getInstance();
        Calendar aft = Calendar.getInstance();
        bef.setTime(sdf.parse(birthday));
        aft.setTime(sdf.parse(nowdata));
        int result = aft.get(Calendar.MONTH) - bef.get(Calendar.MONTH);
        int month = (aft.get(Calendar.YEAR) - bef.get(Calendar.YEAR)) * 12;
        int moth = Math.abs(month + result);
        int yearAge = moth / 12;
        int mothAge = moth % 12;
        return yearAge + "岁" + mothAge + "个月";
    }

    //判断是否session有值
    private Boolean Continue(){
        HttpSession session = request.getSession();
        if(null!=session.getAttribute(CONTINUE)){
            return true;
        }
        return false;
    }

    //获得当前能力年龄
    private Map getDqnlnlMap(){
        Map dqnlnlMap = new HashMap();
        dqnlnlMap.put("1", "4岁-5岁");
        dqnlnlMap.put("2", "6岁-7岁");
        dqnlnlMap.put("3", "8岁-9岁");
        dqnlnlMap.put("4", "10岁-11岁");
        dqnlnlMap.put("5", "12岁-14岁");
        dqnlnlMap.put("6", "14岁以上");
        return dqnlnlMap;
    }

    //获得当前年级
    private Map getDqnlnjMap() {
        Map dqnlnjMap = new HashMap();
        dqnlnjMap.put("-1", "无限制");
        dqnlnjMap.put("0", "学前");
        dqnlnjMap.put("1", "一年级");
        dqnlnjMap.put("2", "二年级");
        dqnlnjMap.put("3", "三年级");
        dqnlnjMap.put("4", "四年级");
        dqnlnjMap.put("5", "五年级");
        dqnlnjMap.put("6", "六年级");
        dqnlnjMap.put("7", "七年级");
        dqnlnjMap.put("8", "八年级");
        dqnlnjMap.put("9", "九年级");
        return dqnlnjMap;
    }


    //获得当前等级
    private Map getDqnddjMap() {
        Map dqnddjMap = new HashMap();
        dqnddjMap.put("-1", "无限制");
        dqnddjMap.put("1", "低");
        dqnddjMap.put("2", "中");
        dqnddjMap.put("3", "高");
        return dqnddjMap;
    }

    //获得当前等级
    private Map getVqtMap() {
        Map vqtMap = new HashMap();
        vqtMap.put("0", "低优先");
        vqtMap.put("1", "高优先");
        return vqtMap;
    }


}


